import 'dart:async';

import 'package:flutter/material.dart';

///@author:create by BZY
///Date: 2022/6/29 08:41
///Description:直播时长组件
class TimeCounter extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TimeCounterState();
}

class TimeCounterState extends State<TimeCounter> {
  var _count = 0;
  Timer? _timer;
  double opacity = 1.0;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    initTimer();
  }

  void initTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (time) {
      setState(() {
        _count++;
        opacity = _count % 2 == 0 ? 1.0 : 0.0;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        AnimatedOpacity(
          opacity: opacity,
          duration: const Duration(milliseconds: 200),
          child: Container(
            width: 6,
            height: 6,
            margin: const EdgeInsets.only(right: 4),
            decoration:
                const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
          ),
        ),
        Text(
          formatTime(),
          style: const TextStyle(fontSize: 12, color: Colors.white),
        )
      ],
    );
  }

  String formatTime() {
    var hour = (_count ~/ 3600).toString().padLeft(2, '0');
    var min = (_count ~/ 60).toString().padLeft(2, '0');
    var second = (_count % 60).toString().padLeft(2, '0');
    return '$hour:$min:$second';
  }
}
